/* 
 * File:   ClientChallenge.cpp
 * Author: Denys Knertser
 * 
 * Created on February 16, 2012, 12:51 AM
 */

using namespace std;

#include "ClientChallenge.h"

ClientChallenge::ClientChallenge() {
    generateChallengeValue();
    challenge=data;
    encryptChallengeValue();
    identifier=0;
    code=0;
    length=data.length();
}

string ClientChallenge::getChallenge() {
    return challenge;
}

int ClientChallenge::generateChallengeValue() {
    //we assume here by default the value_size to be 16 octets
    unsigned char* buf=new unsigned char[16];
    int result=RAND_pseudo_bytes(buf,16);
    data.assign((const char*)buf,16);
    delete(buf);
    return result;
}

int ClientChallenge::encryptChallengeValue() {
    FILE *keyfile = fopen("pubkey.pem", "r");
    if (keyfile==NULL) {
        cout << "Could not find server RSA public key: pubkey.pem\n";
        exit(1);
    }
    RSA *key = PEM_read_RSA_PUBKEY(keyfile, NULL, NULL, NULL);
    fclose(keyfile);
    unsigned char* buf=new unsigned char[128];
    int result=RSA_public_encrypt(data.length(),(unsigned char*) data.c_str(), buf, key, RSA_PKCS1_PADDING);
    data.assign((const char*)buf,result);
    return result;
}